/*
 * @des: 网络请求
 * @author: yyq
 * @Date: 201-01-05
*/


import {
	baseUrl
} from './env'
import querystring from 'querystring';


export default async(url = '', data = {}, type = 'POST', contentType = null, domId = null) => {
	type = type.toUpperCase();
	url = baseUrl + url;

	// 添加时间戳
	data.t = new Date().getTime();

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}else if (type == 'POST') {
		if (contentType == 'multipart/form-data') { // 文件流方式
			let fd = new FormData(document.getElementById(domId));
			Object.keys(data).forEach(key => {
				fd.append(key, data[key]);
			})
			var requestConfig = {
				credentials: 'include',
				method: type,
				mode: "cors",
				body: fd
			};
		}else { // 默认方式
			var requestConfig = {
				credentials: 'include',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				},
				method: type,
				mode: "cors"
			};
			Object.defineProperty(requestConfig, 'body', {
				value: querystring.stringify(data)
			})
		}
	}

	try {
		const response = await fetch(url, requestConfig);
		const responseJson = await response.json();

		// 根据状态码转换
		if (responseJson.retStatus == responseStatus.timeout) {
			router.push('/login');
		}else {
			return responseJson
		}
	} catch (error) {
		layer.msg('请求失败，请检查网络状态，再重试！', {
			offset: '100px',
			icon: 2
		});
		throw new Error(error)
	}
}